<template>
  <div class="student-advisor-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <h2>学生指导老师分配管理</h2>
          <div class="header-actions">
            <el-button type="primary" @click="showBatchAssignDialog = true">
              <el-icon><UserFilled /></el-icon>
              批量分配
            </el-button>
            <el-button @click="fetchData">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
        </div>
      </template>

      <!-- 统计信息 -->
      <div class="statistics-section">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-statistic title="总学生数" :value="statistics.totalStudents" />
          </el-col>
          <el-col :span="6">
            <el-statistic title="已分配学生" :value="statistics.assignedStudents" />
          </el-col>
          <el-col :span="6">
            <el-statistic title="未分配学生" :value="statistics.unassignedStudents" />
          </el-col>
          <el-col :span="6">
            <el-statistic title="指导老师数" :value="statistics.totalTeachers" />
          </el-col>
        </el-row>
      </div>

      <!-- 搜索筛选 -->
      <div class="search-section">
        <el-form :model="searchForm" inline>
          <el-form-item label="学生姓名">
            <el-input v-model="searchForm.name" placeholder="请输入学生姓名" clearable />
          </el-form-item>
          <el-form-item label="学号">
            <el-input v-model="searchForm.student_id" placeholder="请输入学号" clearable />
          </el-form-item>
          <el-form-item label="分配状态">
            <el-select v-model="searchForm.advisor_status" placeholder="请选择" clearable>
              <el-option label="已分配" value="assigned" />
              <el-option label="未分配" value="unassigned" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 学生列表 -->
      <div class="table-section">
        <el-table 
          :data="studentList" 
          v-loading="loading"
          stripe
          border
        >
          <el-table-column prop="student_id" label="学号" width="120" />
          <el-table-column prop="name" label="姓名" width="100" />
          <el-table-column prop="gender" label="性别" width="80">
            <template #default="{ row }">
              {{ row.gender === 'M' ? '男' : '女' }}
            </template>
          </el-table-column>
          <el-table-column prop="grade.name" label="年级" width="100" />
          <el-table-column prop="phone" label="联系电话" width="130" />
          <el-table-column label="指导老师" width="150">
            <template #default="{ row }">
              <el-tag v-if="row.advisor" type="success">
                {{ row.advisor.username }}
              </el-tag>
              <el-tag v-else type="warning">未分配</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="resume_status" label="简历状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getResumeStatusType(row.resume_status)">
                {{ getResumeStatusText(row.resume_status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button 
                type="primary" 
                size="small" 
                @click="handleAssignAdvisor(row)"
              >
                {{ row.advisor ? '重新分配' : '分配老师' }}
              </el-button>
              <el-button 
                v-if="row.advisor" 
                type="danger" 
                size="small" 
                @click="handleRemoveAdvisor(row)"
              >
                取消分配
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="pagination.page"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>

    <!-- 分配老师对话框 -->
    <el-dialog
      v-model="showAssignDialog"
      title="分配指导老师"
      width="500px"
    >
      <el-form :model="assignForm" label-width="100px">
        <el-form-item label="学生">
          <el-input :value="currentStudent?.name" disabled />
        </el-form-item>
        <el-form-item label="学号">
          <el-input :value="currentStudent?.student_id" disabled />
        </el-form-item>
        <el-form-item label="指导老师" required>
          <el-select 
            v-model="assignForm.advisor_id" 
            placeholder="请选择指导老师"
            filterable
            clearable
          >
            <el-option
              v-for="teacher in teacherList"
              :key="teacher.id"
              :label="`${teacher.username} (${teacher.student_count || 0}个学生)`"
              :value="teacher.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAssignDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmAssign" :loading="assigning">
          确定分配
        </el-button>
      </template>
    </el-dialog>

    <!-- 批量分配对话框 -->
    <el-dialog
      v-model="showBatchAssignDialog"
      title="批量分配指导老师"
      width="600px"
    >
      <div class="batch-assign-content">
        <el-alert
          title="批量分配说明"
          description="可以选择多个学生，为他们分配同一个指导老师"
          type="info"
          show-icon
          :closable="false"
        />
        
        <el-form :model="batchAssignForm" label-width="100px" style="margin-top: 20px;">
          <el-form-item label="指导老师" required>
            <el-select 
              v-model="batchAssignForm.advisor_id" 
              placeholder="请选择指导老师"
              filterable
            >
              <el-option
                v-for="teacher in teacherList"
                :key="teacher.id"
                :label="`${teacher.username} (当前${teacher.student_count || 0}个学生)`"
                :value="teacher.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="选择学生">
            <el-transfer
              v-model="batchAssignForm.student_ids"
              :data="unassignedStudentOptions"
              :titles="['未分配学生', '待分配学生']"
              filterable
              filter-placeholder="搜索学生"
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button @click="showBatchAssignDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmBatchAssign" :loading="batchAssigning">
          批量分配
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, UserFilled } from '@element-plus/icons-vue'
import { studentApi } from '@/api/student'

// 响应式数据
const loading = ref(false)
const assigning = ref(false)
const batchAssigning = ref(false)
const showAssignDialog = ref(false)
const showBatchAssignDialog = ref(false)

const studentList = ref([])
const teacherList = ref([])
const currentStudent = ref(null)

const statistics = reactive({
  totalStudents: 0,
  assignedStudents: 0,
  unassignedStudents: 0,
  totalTeachers: 0
})

const searchForm = reactive({
  name: '',
  student_id: '',
  advisor_status: ''
})

const assignForm = reactive({
  advisor_id: null
})

const batchAssignForm = reactive({
  advisor_id: null,
  student_ids: []
})

const pagination = reactive({
  page: 1,
  pageSize: 20,
  total: 0
})

// 计算属性
const unassignedStudentOptions = computed(() => {
  return studentList.value
    .filter(student => !student.advisor)
    .map(student => ({
      key: student.id,
      label: `${student.name} (${student.student_id})`
    }))
})

// 方法
const fetchData = async () => {
  await Promise.all([
    fetchStudentList(),
    fetchTeacherList(),
    fetchStatistics()
  ])
}

const fetchStudentList = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      page_size: pagination.pageSize,
      ...searchForm
    }
    const response = await studentApi.getStudentList(params)
    studentList.value = response.data.results
    pagination.total = response.data.count
  } catch (error) {
    ElMessage.error('获取学生列表失败')
  } finally {
    loading.value = false
  }
}

const fetchTeacherList = async () => {
  try {
    const response = await studentApi.getAdvisorStatistics()
    teacherList.value = response.data.teachers
  } catch (error) {
    ElMessage.error('获取老师列表失败')
  }
}

const fetchStatistics = async () => {
  try {
    const response = await studentApi.getAdvisorStatistics()
    statistics.totalTeachers = response.data.total_teachers
    statistics.unassignedStudents = response.data.unassigned_students
    statistics.assignedStudents = statistics.totalStudents - statistics.unassignedStudents
  } catch (error) {
    console.error('获取统计信息失败:', error)
  }
}

// 事件处理
const handleSearch = () => {
  pagination.page = 1
  fetchStudentList()
}

const resetSearch = () => {
  Object.assign(searchForm, {
    name: '',
    student_id: '',
    advisor_status: ''
  })
  handleSearch()
}

const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.page = 1
  fetchStudentList()
}

const handleCurrentChange = (page: number) => {
  pagination.page = page
  fetchStudentList()
}

const handleAssignAdvisor = (student: any) => {
  currentStudent.value = student
  assignForm.advisor_id = student.advisor?.id || null
  showAssignDialog.value = true
}

const handleRemoveAdvisor = async (student: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要取消 ${student.name} 的指导老师分配吗？`,
      '确认取消分配',
      { type: 'warning' }
    )
    
    await studentApi.assignAdvisor({
      student_id: student.id,
      advisor_id: null
    })
    
    ElMessage.success('取消分配成功')
    fetchData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('取消分配失败')
    }
  }
}

const confirmAssign = async () => {
  if (!assignForm.advisor_id) {
    ElMessage.warning('请选择指导老师')
    return
  }
  
  assigning.value = true
  try {
    await studentApi.assignAdvisor({
      student_id: currentStudent.value.id,
      advisor_id: assignForm.advisor_id
    })
    
    ElMessage.success('分配成功')
    showAssignDialog.value = false
    fetchData()
  } catch (error) {
    ElMessage.error('分配失败')
  } finally {
    assigning.value = false
  }
}

const confirmBatchAssign = async () => {
  if (!batchAssignForm.advisor_id) {
    ElMessage.warning('请选择指导老师')
    return
  }
  
  if (batchAssignForm.student_ids.length === 0) {
    ElMessage.warning('请选择要分配的学生')
    return
  }
  
  batchAssigning.value = true
  try {
    const assignments = batchAssignForm.student_ids.map(studentId => ({
      student_id: studentId,
      advisor_id: batchAssignForm.advisor_id
    }))
    
    await studentApi.batchAssignAdvisor({ assignments })
    
    ElMessage.success('批量分配成功')
    showBatchAssignDialog.value = false
    batchAssignForm.student_ids = []
    fetchData()
  } catch (error) {
    ElMessage.error('批量分配失败')
  } finally {
    batchAssigning.value = false
  }
}

// 辅助方法
const getResumeStatusType = (status: string) => {
  const typeMap = {
    'not_started': 'info',
    'in_progress': 'warning',
    'submitted': 'primary',
    'approved': 'success',
    'rejected': 'danger'
  }
  return typeMap[status] || 'info'
}

const getResumeStatusText = (status: string) => {
  const textMap = {
    'not_started': '未开始',
    'in_progress': '制作中',
    'submitted': '已提交',
    'approved': '已通过',
    'rejected': '需修改'
  }
  return textMap[status] || status
}

// 生命周期
onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.student-advisor-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.statistics-section {
  margin-bottom: 20px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.search-section {
  margin-bottom: 20px;
  padding: 20px;
  background: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
}

.table-section {
  background: #fff;
}

.pagination-wrapper {
  margin-top: 20px;
  text-align: right;
}

.batch-assign-content {
  max-height: 500px;
  overflow-y: auto;
}
</style>
